#pragma once

#include <iostream>
#include <string>
#include <cstring>
#include <stdlib.h>

#include <unistd.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/shm.h>

#include <sys/types.h>
#include <sys/stat.h>

#include "log.hpp"

Log lg;
const std::string pathname = "/home/alin";
const int proj_id = 0x6666;
// const int proj_id = 1024 ^ getpid();
const int size = 4096;

// 获取key值
key_t GetKey()
{
    key_t key = ftok(pathname.c_str(), proj_id);
    if (key < 0)
    {
        lg(Fatal, "ftok error: %d, strerror: %s", errno, strerror(errno));
        exit(1);
    }
    lg(Info, "ftok success, key is : 0x%x", key);
    return key;
}

// 由flag 来标记怎样申请共享内存
int GetShareMemHelper(int flag)
{
    key_t k = GetKey();
    int shmid = shmget(k, size, flag);
    if (shmid < 0)
    {
        lg(Fatal, "create share memory error: %d, strerror: %s", errno, strerror(errno));
        exit(2);
    }
    lg(Info, "create share memory success, shmid is : %d", shmid);

    return shmid;
}

// 创建共享内存
int CreateShm()
{
    return GetShareMemHelper(IPC_CREAT | IPC_EXCL | 0666);
}

// 获取共享内存
int GetShm()
{
    return GetShareMemHelper(IPC_CREAT);
}

// 使用有名管道来实现同步机制
#define FIFO_FILE "./myfifo"
#define MODE 0666

enum
{
    FIFO_CREATE_ERR = 1,
    FIFO_DELETE_ERR,
    FIFO_OPEN_ERR
};

class Init
{
public:
    Init()
    {
        // 创建管道
        int n = mkfifo(FIFO_FILE, MODE);
        if (n < -1)
        {
            perror("mkfifo");
            exit(FIFO_CREATE_ERR);
        }
    }
    ~Init()
    {

        int m = unlink(FIFO_FILE);
        if (m < -1)
        {
            perror("unlink");
            exit(FIFO_DELETE_ERR);
        }
    }
};